package com.legsem.jhosync.ws.rs;

import java.io.InputStream;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;

import com.legsem.jhosync.Server;
import com.legsem.jhosync.dto.ClientLogin;

@Path("clientlogin")
public class ClientLoginResource extends AbstractResource {

    @POST
    @Consumes("application/json")
    public Response clientLogin(InputStream clientLoginPayload,
            @Context HttpServletRequest req) {
        try {
            ClientLogin clientLogin = getMapper().readValue(clientLoginPayload,
                    ClientLogin.class);
            Server server = getServer(req);
            server.doLogout();
            if (server.doLogin(clientLogin)) {
                return Response.ok().build();
            } else {
                return Response.status(401).build();
            }

        } catch (Exception e) {
            throw new WebApplicationException(e,
                    Response.Status.INTERNAL_SERVER_ERROR);
        }
    }

    @GET
    public Response clientLoginFromBrowser(@QueryParam("login") String login,
            @QueryParam("password") String password,
            @Context HttpServletRequest req) {
        try {
            ClientLogin clientLogin = new ClientLogin();
            clientLogin.setLogin(login);
            clientLogin.setPassword(password);
            Server server = getServer(req);
            server.doLogout();
            if (server.doLogin(clientLogin)) {
                return Response.ok().build();
            } else {
                return Response.status(401).build();
            }

        } catch (Exception e) {
            throw new WebApplicationException(e,
                    Response.Status.INTERNAL_SERVER_ERROR);
        }
    }
}
